<template>
  <div>
    <h1>本机网络接口信息</h1>
    <button @click="startDiscovery" :disabled="isScanning">
      {{ isScanning ? '正在扫描...' : '扫描网络接口' }}
    </button>
    <ul>
      <li v-for="(interfaced, index) in networkInterfaces" :key="index">
        IP地址: {{ interfaced.ip }} - 类型: {{ interfaced.type }}
      </li>
    </ul>
  </div>
</template>

<script>
import Peer from "simple-peer/simplepeer.min.js";
import { v4 as uuidv4 } from "uuid";

export default {
  data() {
    return {
      networkInterfaces: [],
      isScanning: false
    };
  },
  methods: {
    async startDiscovery() {
      this.isScanning = true;
      this.networkInterfaces = [];

      try {
        const pc = new RTCPeerConnection({
          iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
        });

        pc.onicecandidate = (event) => {
          if (event.candidate) {
            // 解析 ICE candidate 中的 IP 地址信息
            const candidate = event.candidate;
            const ip = this.extractIPFromCandidate(candidate.candidate);
            if (ip) {
              // 避免重复添加相同的 IP
              if (!this.networkInterfaces.some(inf => inf.ip === ip)) {
                this.networkInterfaces.push({
                  ip: ip,
                  type: candidate.candidate.includes('host') ? '本地网卡' : '公网地址'
                });
              }
            }
          }
        };

        // 创建一个数据通道来触发 ICE 候选收集
        pc.createDataChannel('dummy');
        const offer = await pc.createOffer();
        await pc.setLocalDescription(offer);

        // 5秒后关闭连接
        setTimeout(() => {
          pc.close();
          this.isScanning = false;
        }, 5000);

      } catch (error) {
        console.error('扫描出错：', error);
        this.isScanning = false;
      }
    },

    extractIPFromCandidate(candidateStr) {
      // 使用正则表达式匹配 IP 地址
      const matches = candidateStr.match(/([0-9]{1,3}\.){3}[0-9]{1,3}/);
      if (matches && matches[0]) {
        const ip = matches[0];
        // 过滤掉不需要的 IP 地址
        if (!ip.startsWith('0.0.0.0') && 
            !ip.startsWith('127.0.0.1') && 
            !ip.startsWith('169.254')) {
          return ip;
        }
      }
      return null;
    }
  }
};
</script>

<style scoped>
button {
  margin: 10px 0;
  padding: 8px 16px;
  cursor: pointer;
}

button:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  margin: 8px 0;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>